package com.paipai.config;

import com.paipai.entity.User;
import com.paipai.utils.CookieUtils;
import com.paipai.utils.JwtUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Configuration
public class FeignConfig implements RequestInterceptor {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public void apply(RequestTemplate requestTemplate) {

        //从cookie中取值
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attrs.getRequest();
        System.out.println("---------cookies---------"+ Arrays.toString(req.getCookies()));
        String token = CookieUtils.getCookie("token", req);
        String username = CookieUtils.getCookie("account", req);
        System.out.println(username);
        System.out.println(token);

        System.out.println("------requestTemplate.url()--------"+requestTemplate.feignTarget());

        String url = requestTemplate.toString();

        if(!StringUtils.isEmpty(username)|| Objects.equals(username, "null")) {
            try {
                System.out.println(username);
                String tokenName = JwtUtils.getAccount(token);
                System.out.println("-------tokenName---------"+tokenName);
                requestTemplate.header("token", token);
            }catch (Exception e){
//                e.printStackTrace();
            }
        }
    }



}
